package kuaishou

import (
	"GoServer/utils/config"
	"GoServer/utils/databases"
	"GoServer/utils/debug"
	"GoServer/utils/tool"
	"context"
	"encoding/json"
	"fmt"
	"time"
)

/*
*
请求小玩法access_token
*/
type RequsetToken struct {
	Appid     string `json:"app_id"`     //小程序 ID
	Secret    string `json:"app_secret"` //小程序的 APP Secret，可以在开发者后台获取
	GrantType string `json:"grant_type"` //获取 access_token 时值为 client_credential
}

type KuaishouTokenBody struct {
	Result      int    `json:"result"`
	AccessToken string `json:"access_token"`
	ExpiresIn   int64  `json:"expires_in"`
	TokenType   string `json:"token_type"`
}

//var DYAccessToken string = "080112184633413238794e6b6f6236693239592b534f676574513d3d" /// access_token

// / 初始化抖音Access_token刷新定时器
func RefreshAccessToken(gameName string) {
	tool.Timer(
		1,
		time.Duration(config.GetConfig("app").GetInt("kuaishou.refreshAccessToken"))*time.Second,
		GetAccessToken,
		map[string]string{
			"game_name": gameName,
		})
}

func GetAccessToken(param interface{}) (result bool) {
	params, ok := param.(map[string]string)
	if !ok {
		fmt.Println("参数格式错误")
		return false
	}
	game_name := params["game_name"]
	result = true
	defer func() {
		if r := recover(); !tool.InterfaceIsNil(r) {
			debug.Logln(debug.Error, "cleanConnection err", r)
		}
	}()
	debug.Logln(debug.Info, "定时刷新快手：access_token")
	data := &RequsetToken{
		Appid:     config.GetConfig("app").GetString(game_name + ".appid"),
		Secret:    config.GetConfig("app").GetString(game_name + ".appSecret"),
		GrantType: config.GetConfig("app").GetString("kuaishou.grantType"),
	}
	queryParams := tool.StructToQueryMap(data)

	resp, err := tool.SendHttpRequest("GET", config.GetConfig("app").GetString("kuaishou.getAccessTokenUrl"), queryParams, "", nil)
	msg := KuaishouTokenBody{}
	if err = json.Unmarshal(resp, &msg); err != nil {
		debug.Logln(debug.Error, err.Error())
	}
	debug.Logln(debug.Info, fmt.Sprintf("获取Access_token: %+v", msg))
	if msg.Result == 1 {
		///记录快手的token
		saveAccessToke(game_name, msg.AccessToken, msg.ExpiresIn)
	} else {
		debug.Logln(debug.Error, fmt.Sprintf("获取AccessToken错误: %+v", msg))
		return false
	}

	return true
}

func saveAccessToke(gameName string, accessToken string, expires int64) {
	err := databases.Rediss.Set(context.Background(), gameName+"AccessToken", accessToken, time.Duration(expires)*time.Second).Err()
	if err != nil {
		debug.Logln(debug.Error, "Access Token 存入 redis 失败")
	}
}

func GetKSAccessToken(gameName string) string {
	value, err := databases.Rediss.Get(context.Background(), gameName+"AccessToken").Result()
	if err != nil {
		return ""
	}

	return value
}
